package humanMirror.controller.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import humanMirror.model.controller.Controller;

public class QuizAction implements Action {

	Controller controller;
	int questionNumber;
	String[]answers;

	public String perform(HttpServletRequest request,
			HttpServletResponse response) {
		
		controller = (Controller) request.getSession().getAttribute("controller");
		questionNumber = (Integer) request.getSession().getAttribute("questionNumber");
				
		if(questionNumber == 0){	
			request.setAttribute("question", controller.getQuestion(questionNumber));		
			request.getSession().setAttribute("questionNumber", ++questionNumber);
			return "/quiz.jsp";
		} else{
			
			try{
				answers = request.getParameterValues("answers");	
			}catch(Exception e){
				e.printStackTrace();
			}
		
			controller.setAnswers(stringToInt(answers));

			if (questionNumber == controller.getCountOfQuestions()){
				controller.stopAsking();
				request.getSession().setAttribute("questionNumber", 0);
				return "/answers.jsp";
			}else {	
				request.setAttribute("question", controller.getQuestion(questionNumber));
				request.getSession().setAttribute("questionNumber", ++questionNumber);
				return "/quiz.jsp";
			}		
		}
	}//perform

	protected int[] stringToInt(String[] inputArray){
		if (inputArray == null) return new int[]{};
		int[] outPutArray  = new int[inputArray.length];
		for(int i = 0; i < inputArray.length; i++){
			outPutArray[i] = Integer.parseInt(inputArray[i]);
		}
		return outPutArray;		
	}//stringToInt

}
